import { useState, useEffect } from 'react';
import { Form, Input, Checkbox, Button, message } from 'antd';
import axios from 'axios';

const CreateRole = () => {
    const [allPermissions, setAllPermissions] = useState([]);
    const [selectedPermissions, setSelectedPermissions] = useState([]);
    const [form] = Form.useForm();

    // 获取所有权限信息
    const fetchPermissions = async () => {
        try {
            const response = await axios.get(`http://localhost:8080/api/roles/get-all-permissions`);
            if (response.status === 200 && response.data.code === 200) {
                setAllPermissions(response.data.data);
                console.log('获取权限信息成功！');
            } else {
                message.error('获取权限信息失败，请稍后再试！');
            }
        } catch (error) {
            console.error('获取权限信息失败：', error);
            message.error('获取权限信息失败，请稍后再试！');
        }
    };

    useEffect(() => {
        fetchPermissions();
    }, []);

    // 处理权限选择
    const handlePermissionChange = (e, permissionId) => {
        if (e.target.checked) {
            setSelectedPermissions([...selectedPermissions, permissionId]);
        } else {
            setSelectedPermissions(selectedPermissions.filter(id => id !== permissionId));
        }
    };

    // 提交表单,创建新角色
    const onFinish = async (values) => {
        try {
            // 构建请求体
            const requestBody = {
                roleId: values.roleId,
                roleName: values.roleName,
                permissionIds: selectedPermissions
            };

            // 打印请求体内容
            console.log('发送的请求体:', requestBody);

            const response = await axios.post(`http://localhost:8080/api/roles`, requestBody);
            const data = response.data;

            if (response.status === 200 && data.code === 200) {
                message.success('角色创建成功！');
                form.resetFields(); // 重置表单
                setSelectedPermissions([]); // 清空选中的权限
                window.history.back();
            } else {
                message.error(data.message || '角色创建失败，请稍后再试！');
            }
        } catch (error) {
            // 捕获错误响应
            if (error.response) {
                // 根据不同的HTTP状态码显示不同的错误消息
                message.error(error.response.data.message || '角色创建失败，请稍后再试！');
            } else {
                console.error('角色创建失败：', error);
                message.error('角色创建失败，请稍后再试！');
            }
        }
    };

    // 取消创建并返回上一页
    const onCancel = () => {
        window.history.back();
    };

    return (
        <div style={{ maxWidth: '600px', margin: '0 auto' }}>
            <h1 style={{ textAlign: 'center' }}>创建新角色</h1>
            <Form
                form={form}
                name="createRole"
                onFinish={onFinish}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 14 }}
                layout="horizontal"
            >
                <Form.Item
                    label="角色ID"
                    name="roleId"
                    rules={[{ required: true, message: '请输入角色ID!' }]}
                >
                    <Input style={{ width: '100%', maxWidth: '300px' }} />
                </Form.Item>

                <Form.Item
                    label="角色名称"
                    name="roleName"
                    rules={[{ required: true, message: '请输入角色名称!' }]}
                >
                    <Input style={{ width: '100%', maxWidth: '300px' }} />
                </Form.Item>

                <Form.Item label="权限选择" style={{ marginBottom: 0 }}>
                    {allPermissions.map(permission => (
                        <Form.Item key={permission.permissionId} valuePropName="checked" style={{ display: 'inline-block', marginRight: '10px' }}>
                            <Checkbox
                                checked={selectedPermissions.includes(permission.permissionId)}
                                onChange={(e) => handlePermissionChange(e, permission.permissionId)}
                            >
                                {permission.permissionName}
                            </Checkbox>
                        </Form.Item>
                    ))}
                </Form.Item>

                <Form.Item style={{  display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
                    <div style={{ display: 'flex', justifyContent: 'center', width: '100%' ,gap: '10px'}}>
                        <Button type="primary" htmlType="submit" style={{  width: '200px' ,marginLeft: '50px'}}>
                            确认创建
                        </Button>
                        <Button onClick={onCancel} style={{  width: '200px'}}>
                            取消
                        </Button>
                        </div>
                </Form.Item>
            </Form>
        </div>
    );
};

export default CreateRole;